package com.histone.heartbeat.web;

import com.histone.heartbeat.pojo.UserEntity;
import com.histone.heartbeat.pojo.resp.ResultBean;
import com.histone.heartbeat.service.ContactVerifyService;
import com.histone.heartbeat.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private ContactVerifyService contactVerifyService;

    @GetMapping("{userid}")
    public ResultBean getUser(@PathVariable String userid){
        UserEntity user = userService.getUser(userid);
        return new ResultBean(user);
    }

    @PutMapping
    /**
     * 修改用户信息， 禁止接收emailVerify等敏感参数
     */
    public ResultBean saveUser(String userid, String name, String email, String host) throws Exception {
        UserEntity user = userService.getUser(userid);

        // 发送邮箱校验通知
        if (!StringUtils.isEmpty(email) && !email.equalsIgnoreCase(user.getEmail())) {
            contactVerifyService.sendEmailVerify(email, host, userid);
            user.setEmailVerify("N");
        }

        user.setName(name);
        user.setEmail(email);

        user = userService.updateUser(user);
        return new ResultBean(user);
    }

    @GetMapping("id/{code}")
    public String getUserId(@PathVariable String code) {
        return userService.getOpenid(code);
    }

    @GetMapping("/verify/email")
    public String verifyEmail(String email, String userid, String verify) {
        String result = contactVerifyService.verifyEmail(email, userid, verify);
        if ("success".equals(result)){
            UserEntity user = userService.getUser(userid);
            user.setEmailVerify("Y");
            userService.updateUser(user);
            result = "校验成功";
        }

        return result;
    }
}
